package com.apes.fn.crm.customerExpand;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSONObject;
import com.apes.framework.api.DomainService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.outbox.annotation.OutboxSubscriber;
import com.apes.framework.util.LogicalUtil;
import com.apes.scm.masterdata.party.model.AccessProvider;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.product.model.Product;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @program: apes-server
 * @description:
 * @author: czs
 * @create: 2023-04-04 10:30
 **/
@Service("fnCustomerInfoService")
public class FnCustomerInfoService  extends DomainService {

    @Autowired
    private FnCustomerInfoRepository fnCustomerInfoRepository;


    @OutboxSubscriber(name="生成或更新车辆信息表")
    public void generateOrUpdateFnCustomerInfo(FnCustomerExpand fnCustomerExpand){
        String carLicense = fnCustomerExpand.getCarLicense();
        String vendorCode = fnCustomerExpand.getVendorCode();
        if (carLicense==null||"".equals(carLicense))return;
        if (vendorCode==null||"".equals(vendorCode))return;
        FnCustomerInfo fnCustomerInfo = fnCustomerInfoRepository.findByCarLicenseAndVendorCode(carLicense, vendorCode);
        if (fnCustomerInfo==null){
            fnCustomerInfo=new FnCustomerInfo();
            BeanUtils.copyProperties(fnCustomerExpand, fnCustomerInfo, "id");
            fnCustomerInfo.setFnCustomerExpand(fnCustomerExpand);
        }

        if (fnCustomerInfo.getId() != null) {
            fnCustomerInfo.setUserId(fnCustomerExpand.getUserId());
            fnCustomerInfo.setRealname(fnCustomerExpand.getRealname());
            fnCustomerInfo.setMobile(fnCustomerExpand.getMobile());

            fnCustomerInfo.setSex(fnCustomerExpand.getSex());
            fnCustomerInfo.setSexLabel(fnCustomerExpand.getSexLabel());

            fnCustomerInfo.setUserRoleId(fnCustomerExpand.getUserRoleId());
            fnCustomerInfo.setUserRoleName(fnCustomerExpand.getUserRoleName());

            fnCustomerInfo.setCustomerLevelId(fnCustomerExpand.getCustomerLevelId());
            fnCustomerInfo.setCustomerLevelName(fnCustomerExpand.getCustomerLevelName());

            fnCustomerInfo.setCustomerLivenessId(fnCustomerExpand.getCustomerLivenessId());
            fnCustomerInfo.setCustomerLivenessName(fnCustomerExpand.getCustomerLivenessName());
            fnCustomerInfo.setFnCustomerExpand(fnCustomerExpand);
        }
        fnCustomerInfoRepository.save(fnCustomerInfo);
    }


    private Page<FnCustomerInfo> findCarLincence(SimpleRequest request){
        JSONObject jo = request.getJO();
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        AccessProvider accessProvider = null;
        try {
            PartyRole company = request.getCurrentCompany();
            accessProvider = company.queryAccessProvider();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (request.getJO().containsKey("condition")){
            List<Map> newCondition = request.get("condition");
            AccessProvider finalAccessProvider = accessProvider;
            //终端替换接入商
            if (finalAccessProvider!=null){
                newCondition = newCondition.stream()
                        .map(o -> (JSONObject) o)
//                        .filter(jsonObject -> jsonObject.getString("field").equals("terminal"))
                        .map(jsonObject -> {
                            if (jsonObject.getString("field").equals("terminal")) {
                                //平台后台不需要控制接入商
                                if (!jsonObject.getString("value").equals("platformSystem")) {
                                    jsonObject.put("field", "vendorCode");
                                    jsonObject.put("value", finalAccessProvider.getId());
                                    return jsonObject;
                                }
                                return null;
                            } else {
                                return jsonObject;
                            }

                        })
                        .filter(Objects::nonNull)
                        .collect(Collectors.toList());
            }
            //查询
            return fnCustomerInfoRepository.findAll(
                            JpaDsl.toCriteria(newCondition), PageRequest.of(request.get("page"), request.get("size"))
                    );
        }

        String key1 = jo.getString("key").replace(" ","");
        String key = "%"+ key1 +"%";
        String keyUp = key.toUpperCase();

        Page<FnCustomerInfo> customerInfos ;

        Pattern pattern = Pattern.compile("\\d");
        Matcher numericMatcher = pattern.matcher(key);

        pattern = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher chineseMatcher = pattern.matcher(key);


        PageRequest pageable = PageRequest.of(request.get("page"), request.get("size"), sort);
        //如果平台后台则不需要判断控制权限
        JSONObject jsonObject = jo.getJSONObject("group").getJSONArray("filters").stream()
                .map(o -> ((JSONObject) o))
                .filter(j -> j.getString("field").equals("terminal"))
                .findAny()
                .orElse(new JSONObject());
        String value = jsonObject.getString("value");
        if ( Objects.nonNull(value) && value.equals("platformSystem")) accessProvider = null;

        customerInfos = findCustomerInfos(key, keyUp, numericMatcher, chineseMatcher, pageable, accessProvider);
        return customerInfos;
    }

    private Page<FnCustomerInfo> findCustomerInfos(String key, String keyUp, Matcher numericMatcher, Matcher chineseMatcher, PageRequest pageable,AccessProvider accessProvider) {

        Page<FnCustomerInfo> customerInfos;
        if (accessProvider!=null){
            if (numericMatcher.find()&&chineseMatcher.find()) {//包含数字并且包含中文

                customerInfos = fnCustomerInfoRepository.findAllByVendorCodeAndCarLicenseLikeOrRealnameLike(accessProvider.getId(),keyUp, key, pageable);
            } else if (numericMatcher.find()&&!chineseMatcher.find()){ //包含数字并且不包含中文

                customerInfos = fnCustomerInfoRepository.findAllByVendorCodeAndCarLicenseLikeOrMobileLike(accessProvider.getId(),keyUp, key, pageable);
            }else if (chineseMatcher.find()&&!numericMatcher.find()){//包含中文但不包含数字

                customerInfos = fnCustomerInfoRepository.findAllByVendorCodeAndCarLicenseLikeOrRealnameLike(accessProvider.getId(),keyUp, key, pageable);
            }else {

                customerInfos = fnCustomerInfoRepository.findAllByVendorCodeAndCarLicenseLikeOrMobileLikeOrRealnameLike(accessProvider.getId(),keyUp, key, key, pageable);
            }
            return customerInfos;
        }

        if (numericMatcher.find()&&chineseMatcher.find()) {//包含数字并且包含中文

            customerInfos = fnCustomerInfoRepository.findAllByCarLicenseLikeOrRealnameLike(keyUp, key, pageable);
        } else if (numericMatcher.find()&&!chineseMatcher.find()){ //包含数字并且不包含中文

            customerInfos = fnCustomerInfoRepository.findAllByCarLicenseLikeOrMobileLike(keyUp, key, pageable);
        }else if (chineseMatcher.find()&&!numericMatcher.find()){//包含中文但不包含数字

            customerInfos = fnCustomerInfoRepository.findAllByCarLicenseLikeOrRealnameLike(keyUp, key, pageable);
        }else {

            customerInfos = fnCustomerInfoRepository.findAllByCarLicenseLikeOrMobileLikeOrRealnameLike(keyUp, key, key, pageable);
        }
        return customerInfos;
    }
}
